package org.credo.thread.pool;

import java.util.Random;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.Future;
import java.util.concurrent.RecursiveTask;
import java.util.concurrent.TimeUnit;

public class java7pool2 {

	public static void main(String[] args) throws InterruptedException, ExecutionException {
		int[] arr = new int[100];
		Random rand = new Random();
		int total = 0;
		for (int i = 0, len = arr.length; i < len; i++) {
			int tmp = rand.nextInt(20);
			System.out.println("temp:" + tmp);
			total += (arr[i] = tmp);
		}
		System.out.println("total:" + total);
		ForkJoinPool pool = new ForkJoinPool();
		Future<Integer> future = pool.submit(new CalTask(arr, 0, arr.length));
		System.out.println("返回值为:" + future.get());
		pool.shutdown();
		pool.awaitTermination(2, TimeUnit.SECONDS);
	}

}

class CalTask extends RecursiveTask<Integer> {
	private static final long serialVersionUID = 1L;
	// 每个小任务最多只累加20个数
	private static final int THRESHOLD = 20;
	private int arr[];
	private int start;
	private int end;

	// 累加从start到end的数组元素
	public CalTask(int[] arr, int start, int end) {
		this.arr = arr;
		this.start = start;
		this.end = end;
	}

	@Override
	protected Integer compute() {
		int sum = 0;
		// 当end和start之间的差小鱼THRESHOLD时,开始进行实际累加
		if (end - start < THRESHOLD) {
			for (int i = start; i < end; i++) {
				sum += arr[i];
			}
			return sum;
		} else {
			int middle = (start + end) / 2;
			CalTask left = new CalTask(arr, start, middle);
			CalTask right = new CalTask(arr, middle, end);
			left.fork();
			right.fork();
			// 和上一个程序是类似的,同样分解了任务,并调用分解后的任务的fork()方法使得他们并行执行.
			// 但因为RecursiveTask是具有返回值的,所以用join进行合并.
			return left.join() + right.join();
		}
	}

}